package dao

import (
	"admin-api/app/models/entity"
	"admin-api/app/models/response"
	"admin-api/app/models/vo"
	"admin-api/core"
	"gitee.com/molonglove/goboot/gorm"
)

var User = NewUserDao()

type UserDao struct {
	BaseDao[entity.User]
}

func NewUserDao() *UserDao {
	return &UserDao{struct {
		model entity.User
	}{
		model: entity.User{},
	},
	}
}

// Create 创建用户
func (u *UserDao) Create(tx *gorm.DB, user *entity.User) error {
	return tx.Create(user).Error
}

// GetUserByUserName 获取用户信息通过用户名称
func (u *UserDao) GetUserByUserName(username string) (user entity.User, err error) {
	err = core.DB.
		Builder().
		Select().
		From("sys_user").
		Where(gorm.Eq("user_name", username)).
		QExecute(&user).
		Error
	return
}

// GetUserById 获取用户信息
func (u *UserDao) GetUserById(id int64) (user response.UserLoginInfoResponse, err error) {
	err = core.DB.Namespace("user").
		DQuery("getUserById", map[string]any{"SuperId": vo.SUPER_USER_ID, "UserId": id}).
		TSelect(&user).
		Error
	return
}

// Total 查询获取总条数
func (u *UserDao) Total(condition *gorm.DB) (total int64, err error) {
	err = condition.Model(&entity.User{}).Count(&total).Error
	return
}

// Limit 用户获取数据
func (u *UserDao) Limit(condition *gorm.DB, offset int, limit int) (list []response.RolePageResponse, err error) {
	err = condition.Limit(limit).Offset(offset).Model(&entity.User{}).Find(&list).Error
	return
}

// UserPostId 用户岗位
func (u *UserDao) UserPostId(userId int64) (data []int64, err error) {
	err = core.DB.Builder().
		Select(gorm.Field("distinct post_id")).
		From("sys_user_post").
		Where(gorm.Eq("user_id", userId)).
		QExecute(&data).
		Error
	return
}

// UserPostName 用户岗位名称
func (u *UserDao) UserPostName(userId int64) (data []string, err error) {
	err = core.DB.Namespace("post").DQuery("getPostNameByUserId", map[string]any{"UserId": userId}).TSelect(&data).Error
	return
}

// UserRoleId 用户角色
func (u *UserDao) UserRoleId(userId int64) (data []int64, err error) {
	err = core.DB.Builder().
		Select(gorm.Field("distinct role_id")).
		From("sys_user_role").
		Where(gorm.Eq("user_id", userId)).
		QExecute(&data).
		Error
	return
}

// UserRoleName 用户角色名称
func (u *UserDao) UserRoleName(userId int64) (data []string, err error) {
	err = core.DB.Namespace("role").DQuery("userRoleName", map[string]any{"UserId": userId}).TSelect(&data).Error
	return
}
